//
//  HomeVC.swift
//  placepic
//
//  Created by elesahich on 2020/06/29.
//  Copyright © 2020 elesahich. All rights reserved.
//

import UIKit

class FavoritePlaceSearchVC: UIViewController {
    
    @IBOutlet weak var textFieldBackgroundView: UIView!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var nullPageView: UIView!
    @IBOutlet weak var nullPageTitle: UILabel!
    
    let searchTextField: CustomTextField = {
        let txtfield = CustomTextField()
        let attributedString = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 15),
                                NSAttributedString.Key.foregroundColor: UIColor.blueGray30,
        ]
        txtfield.backgroundColor = UIColor.blueGray20
        txtfield.layer.cornerRadius = 6
        txtfield.layer.borderWidth = 1
        txtfield.font = .systemFont(ofSize: 15)
        txtfield.layer.borderColor = UIColor.white.cgColor
        txtfield.clipsToBounds = true
        txtfield.setLeftPaddingPoints(40)
        txtfield.attributedPlaceholder = NSAttributedString(string: "등록하고 싶은 장소를 검색해보세요.", attributes: attributedString)
        return txtfield
    }()
    
    let searchImage: UIImageView = {
        let imageView = UIImageView()
        imageView.image = UIImage(imageLiteralResourceName: "searchBarIc")
        imageView.contentMode = .scaleAspectFill
        imageView.frame = CGRect.zero
        return imageView
    }()
    
    var placeSearchData: [PlaceSearchData] = []
    var placeLargeData: DataClass?
    var classifyText: String?

    override func viewDidLoad() {
        super.viewDidLoad()
        setNavigationBar()
//        setsearchTextFields()
        setupCustomTextField()
        configureTableView()
        configureNullPageView()
        debounceTextField()
        swipeRecognizer()
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
            if let index = tableView.indexPathForSelectedRow {
            tableView.deselectRow(at: index, animated: true)
        }
    }
}

// MARK: - UI
extension FavoritePlaceSearchVC {

    func swipeRecognizer() {
        let popGestureRecognizer = self.navigationController!.interactivePopGestureRecognizer!
        if let targets = popGestureRecognizer.value(forKey: "targets") as? NSMutableArray {
            let gestureRecognizer = UIPanGestureRecognizer()
            gestureRecognizer.setValue(targets, forKey: "targets")
            self.view.addGestureRecognizer(gestureRecognizer)
        }
    }
    private func configureNullPageView() {
        nullPageView.backgroundColor = UIColor.white
        nullPageTitle.font = .boldSystemFont(ofSize: 15)
        nullPageTitle.textColor = UIColor.blueGray30
        nullPageTitle.text = "등록하고 싶은 장소를 검색해보세요."
        
        searchTextField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
    }	
    
    private func configureTableView() {
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        searchTextField.delegate = self
        
    }
    
    private func setupCustomTextField() {
        textFieldBackgroundView.addSubview(searchTextField)

        searchTextField.addSubview(searchImage)
        searchTextField.translatesAutoresizingMaskIntoConstraints = false
        searchImage.translatesAutoresizingMaskIntoConstraints = false

        let constraints = [
            searchTextField.leadingAnchor.constraint(equalTo: textFieldBackgroundView.leadingAnchor, constant: 13),
            searchTextField.topAnchor.constraint(equalTo: textFieldBackgroundView.topAnchor, constant: 6),
            searchTextField.trailingAnchor.constraint(equalTo: textFieldBackgroundView.trailingAnchor, constant: -13),
            searchTextField.heightAnchor.constraint(equalToConstant: 41),
            
            searchImage.leadingAnchor.constraint(equalTo: searchTextField.leadingAnchor, constant: 8),
            searchImage.topAnchor.constraint(equalTo: searchTextField.topAnchor, constant: 8),
            searchImage.widthAnchor.constraint(equalToConstant: 24),
            searchImage.heightAnchor.constraint(equalToConstant: 24)
        ]
        NSLayoutConstraint.activate(constraints)
    }
//    private func setsearchTextFields() {
//        searchsearchTextField.addTarget(self, action: #selector(setDefaultRequest), for: .editingDidEnd)
//        searchsearchTextField.backgroundColor = UIColor.blueGray20
//        searchsearchTextField.layer.cornerRadius = 6
//        searchsearchTextField.layer.borderWidth = 1
//        searchsearchTextField.layer.borderColor = UIColor.white.cgColor
//        searchsearchTextField.clipsToBounds = true
//        searchsearchTextField.setLeftPaddingPoints(30)
//        searchsearchTextField.placeholder = "등록하고 싶은 장소를 검색해보세요."
//    }
    
    private func setNavigationBar() {
        guard let navigationBar = self.navigationController?.navigationBar else { return }
        
        navigationBar.isTranslucent = true
        navigationBar.backgroundColor = UIColor.clear
        navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
        navigationBar.shadowImage = UIImage()
        
        let leftButton: UIBarButtonItem = UIBarButtonItem(image: UIImage(named: "backArrowIc"),
                                                          style: .plain,
                                                          target: self,
                                                          action: #selector(dismissVC))
        navigationItem.leftBarButtonItem = leftButton
        navigationItem.title = "최애장소 등록하기"
    }
    
    @objc private func dismissVC() {
        self.navigationController?.popViewController(animated: true)
    }
}

extension FavoritePlaceSearchVC {
    
    @objc
    private func textFieldDidChange(_ textField: UITextField) {
        if searchTextField.hasText {
            let transform = CGAffineTransform(translationX: 0, y: 500)
            UIView.animate(withDuration: 1,
                           delay: 0,
                           usingSpringWithDamping: 1,
                           initialSpringVelocity: 1,
                           options: .curveEaseIn,
                           animations: {
                            self.nullPageView.transform = transform
            }, completion: nil)
            self.tableView.reloadData()
        } else {
            UIView.animate(withDuration: 1,
                           delay: 0,
                           usingSpringWithDamping: 1,
                           initialSpringVelocity: 1,
                           options: .curveEaseOut,
                           animations: {
                            self.nullPageView.transform = .identity
            }, completion: nil)
            nullPageView.transform = .identity
        }
    }
}


// MARK: - Debounce
extension FavoritePlaceSearchVC {
    func debounceTextField() {
        searchTextField.debounce(delay: 0.3) { text in
            let nonOptionalText = text ?? ""
            self.setDefaultRequest(nonOptionalText)
        }
    }
}

//MARK: - 통신
extension FavoritePlaceSearchVC {
    
    @objc private func setDefaultRequest(_ searchText: String) {
        /// `/search/place/" >>>>> +그룹인덱스+쿼리스트링 : 1?query=`
        ///`@@@@ group Index @@@@` 받아서 확인
      
        PlaceSearchServices.placeSearchServices.getplaceSearchList(1, searchText) { data in
            if let metaData = data {
                self.placeLargeData = metaData
                guard let datum = self.placeLargeData?.result else { return }
                print(datum)
                self.placeSearchData = datum
                self.tableView.reloadData()
            }
        }
    }
}

extension FavoritePlaceSearchVC: UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return placeSearchData.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "FindfavoritePlaceTVC") as? FindfavoritePlaceTVC else {
            return UITableViewCell()
        }
        
        cell.model = placeSearchData[indexPath.row]
        return cell
    }
}

extension FavoritePlaceSearchVC: UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard let label = placeSearchData[indexPath.row].placeName else { return }
        guard let vc = storyboard?.instantiateViewController(identifier: "ArticleUploadVC") as? ArticleUploadVC else {
            return }
        guard let text = classifyText else { return }
        
        print("\(placeSearchData[indexPath.row])\n")
        vc.placeSearchData = placeSearchData[indexPath.row]
        vc.classifyBadge = text
        vc.articleTitle = label
                
        navigationController?.pushViewController(vc, animated: true)
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let rowHeight: CGFloat = 71
        return rowHeight
    }
}

extension FavoritePlaceSearchVC: UITextFieldDelegate {
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
}

class CustomTextField: UITextField {
    deinit {
        self.removeTarget(self, action: #selector(self.editingChanged(_:)), for: .editingChanged)
    }
    private var workItem: DispatchWorkItem?
    private var delay: Double = 0.1
    private var callback: ((String?) -> Void)? = nil
    
    func debounce(delay: Double, callback: @escaping ((String?) -> Void)) {
        print(#function)
        self.delay = delay
        self.callback = callback
        DispatchQueue.main.async {
            self.callback?(self.text)
        }
        self.addTarget(self, action: #selector(self.editingChanged(_:)), for: .editingChanged)
    }
    
    @objc private func editingChanged(_ sender: UITextField) {
        print(#function)
        self.workItem?.cancel()
        let workItem = DispatchWorkItem(block: { [weak self] in
            self?.callback?(sender.text)
        })
        self.workItem = workItem
        DispatchQueue.main.asyncAfter(deadline: .now() + self.delay, execute: workItem)
    }
}





